<template>
  <div class="editor-page">
    <!-- 顶部工具栏 -->
    <div v-if="editorReady" class="toolbar">
      <div class="toolbar-left">
        <button class="btn btn-back" @click="handleBack">
          <span class="btn-icon">←</span>
          返回
        </button>
        <div class="document-info">
          <span class="doc-title">文档编辑</span>
          <span v-if="dirty" class="dirty-indicator">● 未保存</span>
        </div>
      </div>
      <div class="toolbar-right">
        <button class="btn btn-save" :disabled="saving" @click="handleSave">
          <span v-if="saving" class="btn-icon">⏳</span>
          <span v-else class="btn-icon">💾</span>
          {{ saving ? '保存中...' : '保存' }}
        </button>
      </div>
    </div>

    <!-- 编辑器容器 -->
    <div class="editor-wrapper">
      <DocumentEditor
        v-if="editorReady"
        id="docEditor"
        :documentServerUrl="documentServerUrl"
        :config="editorConfig"
        @onDocumentReady="onDocumentReady"
        @onSave="onSave"
        @onError="onError"
        @onDocumentStateChange="onDocumentStateChange"
        @onRequestSaveResult="onRequestSaveResult"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { DocumentEditor } from '@onlyoffice/document-editor-vue'
import { getDocumentEditConfig, forceSaveDocument } from '../services/api'

const route = useRoute()
const router = useRouter()
const documentId = ref(route.params.documentId)
const editorConfig = ref({})
const documentServerUrl = ref('')
const editorReady = ref(false)

const saving = ref(false)
const dirty = ref(false)

const onDocumentReady = () => {
  console.log('Document is ready', documentId.value)
  dirty.value = false
}

const onSave = () => {
  console.log('OnlyOffice内部正在保存...', documentId.value)
}

const onError = (error) => {
  console.error('OnlyOffice Error:', error)
  alert('编辑器加载失败或发生错误，请检查控制台日志。')
}

const onDocumentStateChange = (event) => {
  dirty.value = !!event?.data
}

const onRequestSaveResult = (event) => {
  console.log('onRequestSaveResult:', event)
  if (event?.data === 0) dirty.value = false
  saving.value = false
}

// 外置保存：调用后端代理接口 -> Docs CommandService forcesave -> 回调落盘
const handleSave = async () => {
  try {
    const key = editorConfig.value?.document?.key
    if (!key) {
      alert('缺少 document.key，无法触发保存')
      return
    }
    saving.value = true
    await forceSaveDocument(key)
    alert('已触发保存，请稍候')
    // 真正落盘在后端回调；这里仅提示已触发
  } catch (e) {
    console.error(e)
    alert('触发保存失败')
  } finally {
    saving.value = false
  }
}

const handleBack = () => {
  if (dirty.value) {
    const ok = confirm('有未保存的更改，确定要返回吗？')
    if (!ok) return
  }
  router.back()
}

const loadEditorConfig = async () => {
  try {
    const response = await getDocumentEditConfig(documentId.value)
    const { config } = response.data || {}

    if (!config || typeof config !== 'object') {
      throw new Error('后端未返回 config 或格式不正确')
    }
    const serverUrl = config.documentServerUrl
    if (!serverUrl) {
      throw new Error('config.documentServerUrl 缺失')
    }

    documentServerUrl.value = serverUrl
    editorConfig.value = config
    editorReady.value = true
  } catch (error) {
    console.error('Failed to load editor config:', error)
    alert(`加载文档配置失败：${error.message || error}`)
  }
}

onMounted(() => {
  loadEditorConfig()
})
</script>

<style scoped>
.editor-page {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
  z-index: 1000;
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #e5e7eb;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.document-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.doc-title {
  font-weight: 600;
  color: #1f2937;
}

.dirty-indicator {
  color: #f59e0b;
  font-size: 12px;
  font-weight: 500;
}

.editor-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: white;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s ease;
  text-decoration: none;
}

.btn:hover {
  background: #f9fafb;
  border-color: #9ca3af;
}

.btn:active {
  transform: translateY(1px);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-back {
  background: #446995;
  border-color: #446995;
  color: white;
}

.btn-back:hover {
  background: #3a5a7a;
  color: white;
}

.btn-save {
  background: #446995;
  border-color: #446995;
  color: white;
}

.btn-save:hover:not(:disabled) {
  background: #3a5a7a;
}

.btn-icon {
  font-size: 16px;
  line-height: 1;
}

/* 确保编辑器占满剩余空间 */
:deep(#docEditor) {
  width: 100% !important;
  height: 100% !important;
  min-height: 0;
}
</style>
